<template>
  <div class="pageRoll">
    <el-form
      :model="formModel"
      :rules="formRules"
      ref="formRef"
      label-width="100px"
    >
      <div class="navLine">规格设置</div>
      <div class="spec">规格类型</div>
      <div style="margin-left: 91px; margin-top: -12px; margin-bottom: 10px">
        <el-radio v-model="formModel.limitType" :label="0" class="spec__left"
          >统一规格</el-radio
        >
      </div>
      <div v-if="radioMore">
        <el-radio
          v-model="formModel.limitType"
          :label="1"
          style="margin-left: 100px"
          >多规格</el-radio
        >
      </div>
      <div v-if="!radioMore">
        <el-radio
          v-model="formModel.limitType"
          :label="2"
          style="margin-left: 100px"
          >多规格</el-radio
        >
      </div>
      <div v-if="formModel.limitType == 0">
        <el-form-item
          label="指导价"
          prop="originalPrice"
          style="margin-top: 10px"
        >
          <el-input-number
            :min="0"
            :controls="false"
            v-model="formModel.originalPrice"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="实售价">
          <el-input-number
            :min="0"
            :controls="false"
            v-model="formModel.price"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            :step="1"
            :min="0"
            step-strictly
            :controls="false"
            v-model="formModel.stock"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品限购">
          <el-input-number
            :step="1"
            :min="0"
            step-strictly
            :controls="false"
            v-model="formModel.perLimit"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品重量" v-if="isWeight" prop="weight">
          <el-input-number
            :min="0"
            :controls="false"
            v-model="formModel.weight"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品积分">
          <el-input-number
            :step="1"
            :min="0"
            step-strictly
            :controls="false"
            v-model="formModel.giftPoint"
            placeholder="0"
            style="width: 500px"
          ></el-input-number>
        </el-form-item>
      </div>
      <div v-if="formModel.limitType !== 0">
        <div class="specitem">
          <el-radio
            v-model="formModel.limitType"
            :label="1"
            @change="radioMore = true"
            >统一限购</el-radio
          >
          <div v-if="formModel.limitType !== 2" style="margin-left: 20px">
            <div class="specitem__inp">
              限购
              <el-input
                class="specitem__inp--inside"
                v-model="unifyLimitNum"
                style=" ;"
              ></el-input
              >件
            </div>
            <div class="valueName" style="width: 700px">
              <div class="flex" style="justify-content: space-between">
                <div style="width: 110px">规格值</div>
                <div style="width: 60px">指导价</div>
                <div style="width: 60px">实售价</div>
                <div style="width: 90px">库存</div>
                <div style="width: 60px" v-if="isWeight">重量</div>
                <div style="width: 40px">sku图</div>
                <div style="width: 30px">操作</div>
              </div>
              <div class="valueName__noList" v-if="normsList.length === 0">
                暂无数据~
              </div>
              <div
                class="valueName__List middle"
                v-for="(item, index) in normsList"
                :key="index"
                v-else
              >
                <el-input v-model="item.specs" style="width: 120px"></el-input>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.originalPrice"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.price"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :step="1"
                  :min="0"
                  step-strictly
                  :controls="false"
                  v-model="item.stock"
                  style="width: 100px"
                ></el-input-number>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.weight"
                  style="width: 70px"
                  v-if="isWeight"
                ></el-input-number>
                <el-upload
                  class="productImg__uploader product__productImg"
                  :auto-upload="false"
                  :on-change="uploadSkuImg"
                  action=""
                  :show-file-list="false"
                  style="width: 50px; height: 50px"
                >
                  <i
                    style="width: 50px; height: 50px; line-height: 50px"
                    class="el-icon-plus product__productImg--uploader--icon"
                    @click="productSkuIndex = index"
                    v-if="item.pic === ''"
                  ></i>
                  <img
                    :src="item.pic"
                    alt=""
                    style="width: 50px; height: 50px"
                    @click="productSkuIndex = index"
                    v-else
                  />
                </el-upload>
                <div @click="normsList.splice(index, 1)">删除</div>
              </div>
              <el-button
                type="primary"
                plain
                style="margin-top: 10px"
                size="small"
                @click="addSku"
                >+ 添加规格</el-button
              >
            </div>
          </div>
        </div>
        <div class="specitem">
          <el-radio
            v-model="formModel.limitType"
            :label="2"
            class="specitem__inp"
            @change="radioMore = false"
            >规格限购</el-radio
          >
          <div v-if="formModel.limitType === 2" style="margin-left: 20px">
            <div class="valueName" style="width: 700px">
              <div class="flex" style="justify-content: space-between">
                <div style="width: 150px">规格值</div>
                <div style="width: 100px">指导价</div>
                <div style="width: 100px">实售价</div>
                <div style="width: 100px">库存</div>
                <div style="width: 100px">限购</div>
                <div style="width: 100px" v-if="isWeight">重量</div>
                <div style="width: 70px">sku图</div>
                <div style="width: 40px">操作</div>
              </div>
              <div class="valueName__noList" v-if="normsList.length === 0">
                暂无数据~
              </div>
              <div
                class="valueName__List middle"
                v-for="(item, index) in normsList"
                :key="index"
                v-else
              >
                <el-input v-model="item.specs" style="width: 110px"></el-input>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.originalPrice"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.price"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :step="1"
                  :min="0"
                  step-strictly
                  :controls="false"
                  v-model="item.stock"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :step="1"
                  :min="0"
                  step-strictly
                  :controls="false"
                  v-model="item.perLimit"
                  style="width: 70px"
                ></el-input-number>
                <el-input-number
                  :min="0"
                  :controls="false"
                  v-model="item.weight"
                  style="width: 70px"
                  v-if="isWeight"
                ></el-input-number>
                <el-upload
                  class="productImg__uploader product__productImg"
                  :auto-upload="false"
                  :on-change="uploadSkuImg"
                  action=""
                  :show-file-list="false"
                  style="width: 50px; height: 50px"
                >
                  <i
                    style="width: 50px; height: 50px; line-height: 50px"
                    class="el-icon-plus product__productImg--uploader--icon"
                    @click="productSkuIndex = index"
                    v-if="item.pic === ''"
                  ></i>
                  <img
                    :src="item.pic"
                    alt=""
                    v-else
                    @click="productSkuIndex = index"
                    style="width: 50px; height: 50px"
                  />
                </el-upload>
                <div @click="normsList.splice(index, 1)">删除</div>
              </div>
              <el-button
                type="primary"
                plain
                style="margin-bottom: 20px"
                size="small"
                @click="addSku"
                >+ 添加属性</el-button
              >
            </div>
          </div>
        </div>
        <div class="codeOne">
          商品积分：
          <el-input-number
            :step="1"
            :min="0"
            step-strictly
            :controls="false"
            v-model="formModel.giftPoint"
            style="width: 700px"
            placeholder="0"
          ></el-input-number>
        </div>
      </div>
      <div class="navLine">其他信息</div>
      <el-form-item label="初始销量">
        <el-input-number
          :step="1"
          v-model="formModel.sale"
          :placeholder="0"
          style="width: 500px"
          :min="0"
          step-strictly
          :controls="false"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="服务保障">
        <div v-for="item in serviceAssuranceList" :key="item.name">
          <el-checkbox v-model="item.state">
            <div class="serveMsg">
              <span style="width: 120px">{{ item.name }}</span>
              <span style="color: #c6c6c6">{{ item.text }}</span>
            </div>
          </el-checkbox>
        </div>
      </el-form-item>
      <!-- <el-form-item label="参与接龙"
                    prop="dominoState">
        <el-radio-group v-model="formModel.dominoState">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="2">关闭</el-radio>
        </el-radio-group>
      </el-form-item>-->
    </el-form>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref, Prop, Watch } from "vue-property-decorator";
import { upLoad } from "@/api/index";
import cloneDeep from "lodash/cloneDeep";
import storage from "@/libs/storage";
/**
 * 会员折扣
 */
interface MemberPriceDto {
  id: string;
  memberLevelId: string;
  memberLevelName: string;
  memberPrice: string;
  productId: string;
  skuId: string;
}

/**
 * 规格列表
 */
interface Norms {
  /** 规格值 */
  specs: string;
  /** 指导价 */
  originalPrice: number;
  /** 实售价 */
  price: number;
  /** 商品库存 */
  stock: string;
  /** 商品限购 */
  perLimit: string;
  /** sku图 */
  pic: string;
  /** 初始销量 */
  sale: string;
  /** 商品重量 */
  weight: string;
  id: string;
  lowStock: string;
  memberPriceDtoList: MemberPriceDto[];
  productId: string;
  skuCode: string;
}

/**
 * 编辑销售信息
 */
@Component({})
export default class GoodSellInfo extends Vue {
  @Prop({
    type: Object,
    default() {
      return null;
    },
  })
  readonly goodDetail: any;

  @Prop({
    type: String,
    default() {
      return "";
    },
  })
  logisticsId: any;

  @Watch("logisticsId")
  watchLogisticsId() {
    this.getLogMsg();
  }

  /** 配送设置内容 */
  rections = {
    autoShippingState: 1 /** 设置新增提货点是否自动设置送货上门,0false=禁用,1true=启用 */,
    goodPointIdsPercentage: "",
  };

  radioMore = true;

  formModel = {
    /** 指导价 */
    originalPrice: "0",
    /** 实售价 */
    price: "0",
    /** 商品库存 */
    stock: "0",
    /** 商品限购 */
    perLimit: "0",
    /** 商品积分 */
    giftPoint: "0",
    /** 商品重量 */
    weight: "0",
    /** 单规格id */
    id: "",
    /** 初始销量 */
    sale: "0",
    /** 参与接龙 */
    dominoState: 2,
    /** 限购类型(默认统一规格，0–统一规格，1–统一限购，2–规格限购) */
    limitType: 0
  };

  limitNum = "";

  /** 商品模板 */
  isWeight = false;

  formRules = {
    originalPrice: [
      { required: true, message: "请输入商品指导价", trigger: "blur" },
    ],
    stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
    weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
    dominoState: [
      { required: true, message: "请选择是否开启接龙", trigger: "blur" },
    ]
  };

  /** 上传sku下标 */
  productSkuIndex = 0;

  /** 统一限购数量 */
  unifyLimitNum = "0";

  /** 选择规格列表 */
  normsList: Norms[] = [];

  /** 服务保障 */
  serviceAssuranceList = [
    {
      name: "全场包邮",
      state: false,
      text: "所有商品均无条件包邮",
    },
    {
      name: "7天退换",
      state: false,
      text: "商家承诺7天无理由退换货",
    },
    {
      name: "48小时发货",
      state: false,
      text: "商家承诺订单在48小时内发布",
    },
    {
      name: "假一赔十",
      state: false,
      text: "若收到商品是假冒品牌，可获得十倍赔偿",
    },
    {
      name: "正品保证",
      state: false,
      text: "商家承诺商品正品质量",
    },
  ];

  @Ref()
  readonly formRef: HTMLFormElement;

  mounted() {
    this.setFormModel();
    this.getLogMsg();
  }

  /**
   * 获取物流模板
   */
  getLogMsg() {
    this.isWeight = this.$parent.isWeight;
  }

  /**
   * 还原表单数据
   */
  setFormModel() {
    let goodDetail = this.goodDetail;
    if (storage.get("formModel")) {
      goodDetail = storage.get("formModel");
    }
    if (goodDetail) {
      const formModel = this.formModel;
      for (const key of Object.keys(formModel)) {
        const value = goodDetail[key];
        if (value) {
          formModel[key] = value;
        }
      }
      formModel.weight = goodDetail.weight;
      this.setSkuStocks(goodDetail);
      this.setServiceAssuranceList(goodDetail.serviceIds);
    }
  }

  async getFormModel() {
    try {
      await this.validate();
      const formModel = this.formModel;
      const skuStocks = this.getSkuStocks();
      return {
        unit: "克", // 商品重量
        weight: formModel.weight, // 商品长度
        skuStocks,
        giftPoint: formModel.giftPoint,
        sale: formModel.sale,
        serviceIds: this.getServiceIds(),
        dominoState: formModel.dominoState,
        limitType: formModel.limitType
      };
    } catch (error) {
      console.log(error);
      return Promise.reject(false);
    }
  }

  /**
   * 获取商品sku
   */
  getSkuStocks() {
    const limitType = this.formModel.limitType === 0;
    if (limitType) {
      const formModel = this.formModel as any;
      const skuItem = {
        specs: "",
        originalPrice: formModel.originalPrice,
        price: formModel.price,
        stock: formModel.stock,
        perLimit: formModel.perLimit,
        pic: formModel.pic,
        // sale: formModel.sale,
        id: formModel.id,
        lowStock: formModel.lowStock,
        memberPriceDtoList: [],
        productId: formModel.productId,
        skuCode: "",
        weight: formModel.weight,
      };
      return [skuItem];
    }

    if (!limitType) {
      const normsList = this.normsList;
      const isUnifyLimit = this.formModel.limitType === 1; // 是否为统一限购
      const unifyLimitNum = this.unifyLimitNum;
      const skuStocks = normsList.map((item) => {
        return {
          ...item,
          perLimit: isUnifyLimit ? unifyLimitNum : item.perLimit,
        };
      });
      return skuStocks;
    }
  }

  /**
   * 还原商品sku
   */
  setSkuStocks(detail) {
    const limitType = detail.limitType;
    this.radioMore = detail.limitType = 0 ? false : true;
    const skuStocks = detail.skuStocks;
    if (limitType === 0) {
      const skuStockItem = skuStocks[0];
      const formModel = this.formModel;
      for (const key of Object.keys(formModel)) {
        const value = skuStockItem[key];
        if (value) {
          formModel[key] = value;
        }
      }
    } else {
      if (limitType !== 2) {
        this.unifyLimitNum = skuStocks[0].perLimit;
      }
      this.normsList = cloneDeep(skuStocks);
    }
  }

  /**
   * 对整个表单进行校验
   */
  validate() {
    return this.formModel.limitType === 0
      ? this.formRef.validate()
      : this.validateNormsList();
  }

  validateNormsList() {
    // const isUnifyLimit = this.formModel.limitType === 1; // 是否为统一限购
    // const unifyLimitNum = this.unifyLimitNum;
    // if (isUnifyLimit && !unifyLimitNum) {
    //   return Promise.reject(false);
    // }

    const normsList = this.normsList;
    const flag = normsList.every((item) => {
      const { originalPrice, stock } = item;
      return originalPrice && stock;
    });
    if (flag && normsList.length > 0) {
      return true;
    } else {
      return Promise.reject(false);
    }
  }

  /**
   * 移除表单项的校验结果
   */
  clearValidate() {
    this.formRef.clearValidate();
  }

  /**
   * 获取服务保障
   */
  getServiceIds(): string {
    return this.serviceAssuranceList
      .filter((item) => item.state)
      .map((item) => item.name)
      .join(",");
  }

  /**
   * 还原服务保障
   */
  setServiceAssuranceList(serviceIds = "") {
    this.serviceAssuranceList.forEach((item) => {
      item.state = serviceIds.indexOf(item.name) !== -1;
    });
  }

  /**
   * 添加规格
   */
  addSku() {
    this.normsList.push({
      specs: "",
      originalPrice: 0,
      price: 0,
      stock: "0",
      perLimit: "0",
      pic: "",
      sale: "0",
      weight: "0",
      id: "",
      lowStock: "",
      memberPriceDtoList: [],
      productId: "",
      skuCode: "",
    });
  }

  /**
   * 上传sku
   */
  async uploadSkuImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png"];

    const isLt1M = file.size < 2 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 2MB!");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.normsList[this.productSkuIndex].pic = res.data;
  }
}
</script>
